// Copyright 2011 Google Inc. All rights reserved. 
// Use of this source code is governed by the Apache 2.0 
// license that can be found in the LICENSE file.
package hello

import (
	"fmt"
	"http"
	"io/ioutil"
	"log"
	"strings"
	"os"
	"path/filepath"
	"exp/template"
)

func handle(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello Golang")
}

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello world!")
}

func serveStatic(w http.ResponseWriter, r *http.Request) {

	mimeType := map[string] string {
		"css": "text/css",

		"gif": "image/gif",

		"html": "text/html",

		"ico": "image/x-icon",

		"jpeg": "image/jpeg",

		"jpg": "image/jpeg",

		"js": "text/javascript",

		"json": "application/json",

		"pdf": "application/pdf",

		"png": "image/png",

		"svg": "image/svg+xml",

		"swf": "application/x-shockwave-flash",

		"tiff": "image/tiff",

		"txt": "text/plain",

		"wav": "audio/x-wav",

		"wma": "audio/x-ms-wma",

		"wmv": "video/x-ms-wmv",

		"xml": "text/xml"}
	ERROR_404_FILE := "404.htm"
	fileName := r.URL.Path[1:]
	if fileName == "/" || fileName == "" {
		fileName = "v/index.html"
	}

	fileStr := strings.Split(r.URL.Path, ".")
	if len(fileStr) > 1 {
		fileType := fileStr[1]

		var h = w.Header()
		h.Add("Content-Type", mimeType[fileType])
		w.WriteHeader(0)
	}

	log.Println("ask " + fileName)
	body, err := ioutil.ReadFile(fileName)
	if err != nil {
		log.Println(err)
		errorMsg, _ := ioutil.ReadFile(ERROR_404_FILE)
		body = errorMsg
	}

	fmt.Fprintf(w, "%s",body)
}

type article struct{
	content string
}
func post(w http.ResponseWriter, r *http.Request){
	t, _ := template.New("template_post").ParseFile("post.htm")
	params := &article{content : "hello gae"}
	t.Execute(w, params)
}

func list(w http.ResponseWriter, r *http.Request){
	POST_ROOT := "./posts"
	posts := ls(POST_ROOT)

	var content string
	var post string

	content += "<html>"
	
	content += "<head><title> list </title></head>"
	content += "<body>"
	for i:=0; i < len(posts); i++ {
		post = posts[i]
		content += "<li><a href=posts/"+post+">"+post+"</a></li>"
	}
	content += "</body>"
	content += "</html>"
	fmt.Fprintf(w, "%s", content)
}


func version(w http.ResponseWriter, r *http.Request){
	fmt.Fprintf(w, "Version: %v", 0.1)
}

func init() {
	http.HandleFunc("/", serveStatic)
	http.HandleFunc("/stat", handle)
	http.HandleFunc("/hello", hello)
	http.HandleFunc("/list", list)
	http.HandelFunc("/post", post)
	http.HandleFunc("/version", version)
}

func ls(dir string) []string {
        current_dir,_:= os.Open(dir)

        result, err := current_dir.Readdirnames(0)
        if err != nil {
                panic("read file fail")
        }

        return result
}

func pwd(dir string) string {
        abs_path, err := filepath.Abs(dir)
        if err != nil {
                panic("path not exist")
        }
        return abs_path
}

